//
//  BYMASConstraintMaker.m
//  BYMasonry
//
//  Created by Jonas Budelmann on 20/07/13.
//  Copyright (c) 2013 cloudling. All rights reserved.
//

#import "BYMASConstraintMaker.h"
#import "BYMASViewConstraint.h"
#import "BYMASCompositeConstraint.h"
#import "BYMASConstraint+Private.h"
#import "BYMASViewAttribute.h"
#import "BYView+MASAdditions.h"

@interface BYMASConstraintMaker () <BYMASConstraintDelegate>

@property (nonatomic, weak) MAS_VIEW *view;
@property (nonatomic, strong) NSMutableArray *constraints;

@end

@implementation BYMASConstraintMaker

- (id)initWithView:(MAS_VIEW *)view {
    self = [super init];
    if (!self) return nil;
    
    self.view = view;
    self.constraints = NSMutableArray.new;
    
    return self;
}

- (NSArray *)install {
    if (self.removeExisting) {
        NSArray *installedConstraints = [BYMASViewConstraint installedConstraintsForView:self.view];
        for (BYMASConstraint *constraint in installedConstraints) {
            [constraint uninstall];
        }
    }
    NSArray *constraints = self.constraints.copy;
    for (BYMASConstraint *constraint in constraints) {
        constraint.updateExisting = self.updateExisting;
        [constraint install];
    }
    [self.constraints removeAllObjects];
    return constraints;
}

#pragma mark - BYMASConstraintDelegate

- (void)constraint:(BYMASConstraint *)constraint shouldBeReplacedWithConstraint:(BYMASConstraint *)replacementConstraint {
    NSUInteger index = [self.constraints indexOfObject:constraint];
    NSAssert(index != NSNotFound, @"Could not find constraint %@", constraint);
    [self.constraints replaceObjectAtIndex:index withObject:replacementConstraint];
}

- (BYMASConstraint *)constraint:(BYMASConstraint *)constraint addConstraintWithLayoutAttribute:(NSLayoutAttribute)layoutAttribute {
    BYMASViewAttribute *viewAttribute = [[BYMASViewAttribute alloc] initWithView:self.view layoutAttribute:layoutAttribute];
    BYMASViewConstraint *newConstraint = [[BYMASViewConstraint alloc] initWithFirstViewAttribute:viewAttribute];
    if ([constraint isKindOfClass:BYMASViewConstraint.class]) {
        //replace with composite constraint
        NSArray *children = @[constraint, newConstraint];
        BYMASCompositeConstraint *compositeConstraint = [[BYMASCompositeConstraint alloc] initWithChildren:children];
        compositeConstraint.delegate = self;
        [self constraint:constraint shouldBeReplacedWithConstraint:compositeConstraint];
        return compositeConstraint;
    }
    if (!constraint) {
        newConstraint.delegate = self;
        [self.constraints addObject:newConstraint];
    }
    return newConstraint;
}

- (BYMASConstraint *)addConstraintWithAttributes:(MASAttribute)attrs {
    __unused MASAttribute anyAttribute = (BYMASAttributeLeft | BYMASAttributeRight | BYMASAttributeTop | BYMASAttributeBottom | BYMASAttributeLeading
                                          | BYMASAttributeTrailing | BYMASAttributeWidth | BYMASAttributeHeight | BYMASAttributeCenterX
                                          | BYMASAttributeCenterY | BYMASAttributeBaseline
                                          | BYMASAttributeFirstBaseline | BYMASAttributeLastBaseline
#if TARGET_OS_IPHONE || TARGET_OS_TV
                                          | BYMASAttributeLeftMargin | BYMASAttributeRightMargin | BYMASAttributeTopMargin | BYMASAttributeBottomMargin
                                          | BYMASAttributeLeadingMargin | BYMASAttributeTrailingMargin | BYMASAttributeCenterXWithinMargins
                                          | BYMASAttributeCenterYWithinMargins
#endif
                                          );
    
    NSAssert((attrs & anyAttribute) != 0, @"You didn't pass any attribute to make.attributes(...)");
    
    NSMutableArray *attributes = [NSMutableArray array];
    
    if (attrs & BYMASAttributeLeft) [attributes addObject:self.view.mas_left];
    if (attrs & BYMASAttributeRight) [attributes addObject:self.view.mas_right];
    if (attrs & BYMASAttributeTop) [attributes addObject:self.view.mas_top];
    if (attrs & BYMASAttributeBottom) [attributes addObject:self.view.mas_bottom];
    if (attrs & BYMASAttributeLeading) [attributes addObject:self.view.mas_leading];
    if (attrs & BYMASAttributeTrailing) [attributes addObject:self.view.mas_trailing];
    if (attrs & BYMASAttributeWidth) [attributes addObject:self.view.mas_width];
    if (attrs & BYMASAttributeHeight) [attributes addObject:self.view.mas_height];
    if (attrs & BYMASAttributeCenterX) [attributes addObject:self.view.mas_centerX];
    if (attrs & BYMASAttributeCenterY) [attributes addObject:self.view.mas_centerY];
    if (attrs & BYMASAttributeBaseline) [attributes addObject:self.view.mas_baseline];
    if (attrs & BYMASAttributeFirstBaseline) [attributes addObject:self.view.mas_firstBaseline];
    if (attrs & BYMASAttributeLastBaseline) [attributes addObject:self.view.mas_lastBaseline];
    
#if TARGET_OS_IPHONE || TARGET_OS_TV
    
    if (attrs & BYMASAttributeLeftMargin) [attributes addObject:self.view.mas_leftMargin];
    if (attrs & BYMASAttributeRightMargin) [attributes addObject:self.view.mas_rightMargin];
    if (attrs & BYMASAttributeTopMargin) [attributes addObject:self.view.mas_topMargin];
    if (attrs & BYMASAttributeBottomMargin) [attributes addObject:self.view.mas_bottomMargin];
    if (attrs & BYMASAttributeLeadingMargin) [attributes addObject:self.view.mas_leadingMargin];
    if (attrs & BYMASAttributeTrailingMargin) [attributes addObject:self.view.mas_trailingMargin];
    if (attrs & BYMASAttributeCenterXWithinMargins) [attributes addObject:self.view.mas_centerXWithinMargins];
    if (attrs & BYMASAttributeCenterYWithinMargins) [attributes addObject:self.view.mas_centerYWithinMargins];
    
#endif
    
    NSMutableArray *children = [NSMutableArray arrayWithCapacity:attributes.count];
    
    for (BYMASViewAttribute *a in attributes) {
        [children addObject:[[BYMASViewConstraint alloc] initWithFirstViewAttribute:a]];
    }
    
    BYMASCompositeConstraint *constraint = [[BYMASCompositeConstraint alloc] initWithChildren:children];
    constraint.delegate = self;
    [self.constraints addObject:constraint];
    return constraint;
}

#pragma mark - standard Attributes

- (BYMASConstraint *)addConstraintWithLayoutAttribute:(NSLayoutAttribute)layoutAttribute {
    return [self constraint:nil addConstraintWithLayoutAttribute:layoutAttribute];
}

- (BYMASConstraint *)left {
    return [self addConstraintWithLayoutAttribute:NSLayoutAttributeLeft];
}

- (BYMASConstraint *)top {
    return [self addConstraintWithLayoutAttribute:NSLayoutAttributeTop];
}

- (BYMASConstraint *)right {
    return [self addConstraintWithLayoutAttribute:NSLayoutAttributeRight];
}

- (BYMASConstraint *)bottom {
    return [self addConstraintWithLayoutAttribute:NSLayoutAttributeBottom];
}

- (BYMASConstraint *)leading {
    return [self addConstraintWithLayoutAttribute:NSLayoutAttributeLeading];
}

- (BYMASConstraint *)trailing {
    return [self addConstraintWithLayoutAttribute:NSLayoutAttributeTrailing];
}

- (BYMASConstraint *)width {
    return [self addConstraintWithLayoutAttribute:NSLayoutAttributeWidth];
}

- (BYMASConstraint *)height {
    return [self addConstraintWithLayoutAttribute:NSLayoutAttributeHeight];
}

- (BYMASConstraint *)centerX {
    return [self addConstraintWithLayoutAttribute:NSLayoutAttributeCenterX];
}

- (BYMASConstraint *)centerY {
    return [self addConstraintWithLayoutAttribute:NSLayoutAttributeCenterY];
}

- (BYMASConstraint *)baseline {
    return [self addConstraintWithLayoutAttribute:NSLayoutAttributeBaseline];
}

- (BYMASConstraint *(^)(MASAttribute))attributes {
    return ^(MASAttribute attrs){
        return [self addConstraintWithAttributes:attrs];
    };
}

- (BYMASConstraint *)firstBaseline {
    return [self addConstraintWithLayoutAttribute:NSLayoutAttributeFirstBaseline];
}

- (BYMASConstraint *)lastBaseline {
    return [self addConstraintWithLayoutAttribute:NSLayoutAttributeLastBaseline];
}

#if TARGET_OS_IPHONE || TARGET_OS_TV

- (BYMASConstraint *)leftMargin {
    return [self addConstraintWithLayoutAttribute:NSLayoutAttributeLeftMargin];
}

- (BYMASConstraint *)rightMargin {
    return [self addConstraintWithLayoutAttribute:NSLayoutAttributeRightMargin];
}

- (BYMASConstraint *)topMargin {
    return [self addConstraintWithLayoutAttribute:NSLayoutAttributeTopMargin];
}

- (BYMASConstraint *)bottomMargin {
    return [self addConstraintWithLayoutAttribute:NSLayoutAttributeBottomMargin];
}

- (BYMASConstraint *)leadingMargin {
    return [self addConstraintWithLayoutAttribute:NSLayoutAttributeLeadingMargin];
}

- (BYMASConstraint *)trailingMargin {
    return [self addConstraintWithLayoutAttribute:NSLayoutAttributeTrailingMargin];
}

- (BYMASConstraint *)centerXWithinMargins {
    return [self addConstraintWithLayoutAttribute:NSLayoutAttributeCenterXWithinMargins];
}

- (BYMASConstraint *)centerYWithinMargins {
    return [self addConstraintWithLayoutAttribute:NSLayoutAttributeCenterYWithinMargins];
}

#endif


#pragma mark - composite Attributes

- (BYMASConstraint *)edges {
    return [self addConstraintWithAttributes:BYMASAttributeTop | BYMASAttributeLeft | BYMASAttributeRight | BYMASAttributeBottom];
}

- (BYMASConstraint *)size {
    return [self addConstraintWithAttributes:BYMASAttributeWidth | BYMASAttributeHeight];
}

- (BYMASConstraint *)center {
    return [self addConstraintWithAttributes:BYMASAttributeCenterX | BYMASAttributeCenterY];
}

#pragma mark - grouping

- (BYMASConstraint *(^)(dispatch_block_t group))group {
    return ^id(dispatch_block_t group) {
        NSInteger previousCount = self.constraints.count;
        group();

        NSArray *children = [self.constraints subarrayWithRange:NSMakeRange(previousCount, self.constraints.count - previousCount)];
        BYMASCompositeConstraint *constraint = [[BYMASCompositeConstraint alloc] initWithChildren:children];
        constraint.delegate = self;
        return constraint;
    };
}

@end
